package com.xian.im.common.utils.bussiness;

import com.xian.im.common.constant.ThreadLocalConstant;
import com.xian.im.common.enums.UniqueTypeGenerateEnums;
import com.xian.im.common.model.session.SessionUser;
import com.xian.im.common.model.vo.UserDetail;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.common.proto.MsgResponse;
import com.xian.im.common.sequence.UniqueSnowFlakeGenerate;
import com.xian.im.common.utils.sys.SpringContextHolder;
import com.xian.im.common.utils.sys.ThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

/**
 * @program: xian-code
 * @description:  目的地
 * @author: liru.xian
 * @create: 2021-01-22 08:48
 **/
public class XimResponseUtil {


    public static MsgResponse buildError(SessionUser session, String msgError, Integer code){
        return build(session,msgError,code);
    }
    public static MsgResponse buildError(SessionUser session){
        return build(session,"",1000);
    }

    public static MsgResponse buildSuccess(SessionUser session){
        return build(session,"ok",1);
    }

    public static MsgResponse build(SessionUser session,String msgError,Integer code){
        MsgResponse response = new MsgResponse();
        MsgRequest request = ThreadLocalUtil.get(ThreadLocalConstant.REQ);
        if (request != null) {
            BeanUtils.copyProperties(request,response);
        }
        UniqueSnowFlakeGenerate uniqueSnowFlakeGenerate = SpringContextHolder.getBean(UniqueSnowFlakeGenerate.class);
        String uniqueId = StringUtils.isBlank(response.getUniqueId()) ?  uniqueSnowFlakeGenerate.getSerialId(UniqueTypeGenerateEnums.xim_MSG.getCode()) : response.getUniqueId();
        response.setUniqueId(uniqueId);
        response.setTimestamp(System.currentTimeMillis()+"");
        if (session != null) {
            UserDetail user = session.build();
            response.setUser(user);
        }
        response.setCode(code);
        response.setMsg(msgError);
        return response;
    }

    /**
     *  限流
     * @param ctx
     * @return
     */
    public static MsgResponse buildLimitError(SessionUser ctx){
        return build(ctx,"当前用户被限制请求频率",1014);
    }

    /**
     * 攻击
     * @param ctx
     * @return
     */
    public static MsgResponse buildAttackError(SessionUser ctx){
        return build(ctx,"请求错误连接断开",1015);
    }
}
